﻿using Dapper;
using Dapper.Contrib.Extensions;
using IN.DataBase.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace IN.DataBase
{
    /// <summary>
    /// 数据库访问基类 
    /// </summary>
    /// <typeparam name="T">实体类类型</typeparam>
    public partial class BaseService<T> : IBaseService<T> where T : class
    {
        Database dbs = Database.Main;

        /// <summary>
        /// 对象的表名
        /// </summary>
        public string TableName { get; set; }

        /// <summary>
        /// 主键属性对象
        /// </summary>
        public PropertyInfo PrimaryKey { get; set; }

       
        public BaseService()
        {
            this.TableName = EntityHelper.GetTableName(typeof(T));
            this.PrimaryKey = EntityHelper.GetSingleKey<T>();
        }
        /// <summary>
        /// 切换连接数据库为 DataDB. 如果使用dataDB 需要调用该方法
        /// 默认使用Main数据库  
        /// </summary>
        public void SetDataDB()
        {
            dbs = Database.Data;
        }
        public void SetMesDataDB()
        {
            dbs = Database.MesData;
        }

        public void SetHistoryDB()
        {
            dbs = Database.HistoryData;
        }
        public string GetTableName()
        {
            if (string.IsNullOrEmpty(TableYear))
            {
                return TableName;
            }
            else
            {

                return TableName + "_" + TableYear;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetTableYear()
        {
            return TableYear;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="year"></param>
        public void SetTableYear(string year)
        {
            TableYear = year;
        }
        /// <summary>
        /// 数据库连接 获取数据库连接  
        /// </summary>
        public IDbConnection Connection
        {
            get
            {
                var connection = ConnectionFactory.CreateConnection(dbs);
                connection.Open();
                return connection;
            }
        }

        /// <summary>
        /// 返回数据库所有的对象集合
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> GetAll()
        {
            using (IDbConnection dbConnection = Connection)
            {
                return dbConnection.GetAll<T>();
            }
        }

        /// <summary>
        /// 返回数据库所有的对象集合
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> GetBySQL(string sql)
        {
            using (IDbConnection dbConnection = Connection)
            {
                return dbConnection.Query<T>(sql);
            }
        }


        /// <summary>
        /// 查询数据库,返回指定ID的对象
        /// </summary>
        /// <param name="id">主键的值</param>
        /// <returns></returns>
        public T FindByID(object id)
        {
            using (IDbConnection dbConnection = Connection)
            {
                return dbConnection.Get<T>(id);
            }
        }

        /// <summary>
        /// 插入指定对象到数据库中
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Insert(T info)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                dbConnection.Insert(info);
                result = true;
            }
            return result;
        }
        /// <summary>
        /// 插入指定对象集合到数据库中
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Insert(IEnumerable<T> list)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Insert(list) > 0;
            }
            return result;
        }

        /// <summary>
        /// 更新对象属性到数据库中
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Update(T info)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Update(info);
            }
            return result;
        }
        /// <summary>
        /// 更新指定对象集合到数据库中
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Update(IEnumerable<T> list)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Update(list);
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除指定对象
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Delete(T info)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Delete(info);
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除指定对象集合
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Delete(IEnumerable<T> list)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Delete(list);
            }
            return result;
        }
        /// <summary>
        /// 根据指定对象的ID,从数据库中删除指定对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <returns></returns>
        public bool Delete(object id)
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                string query = string.Format("DELETE FROM {0} WHERE {1} = @id", TableName, PrimaryKey.Name);
                var parameters = new DynamicParameters();
                parameters.Add("@id", id);

                result = dbConnection.Execute(query, parameters) > 0;
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除所有对象
        /// </summary>
        /// <returns></returns>
        public bool DeleteAll()
        {
            bool result = false;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.DeleteAll<T>();
            }
            return result;
        }

        #region 报表区


        public string TableYear { get; set; }
        public string HistoryTableName { get; set; } = "";



        #endregion


        #region 扩展
        public int ExecuteBySql(string strSql, object dbParameter)
        {
            int result;
            using (IDbConnection dbConnection = Connection)
            {
                result = dbConnection.Execute(strSql, dbParameter);
            }
            return result;
        }
        /// <summary>
        /// 根据指定数据库执行存储过程
        /// </summary>
        /// <param name="databaseLinkId">数据库主键</param>
        /// <param name="procName">存储过程</param>
        /// <param name="dbParameter">参数</param>
        public void ExecuteBySql(string connString, string sql, object dbParameter = null)
        {

            IDbConnection connection = ConnectionFactory.CreateConnection(connString);
            connection.Open();
            using (IDbConnection dbConnection = Connection)
            {
                dbConnection.Execute(sql, dbParameter);
            }
        }
        /// <summary>
        /// 根据指定数据库执行存储过程
        /// </summary>
        /// <param name="databaseLinkId">数据库主键</param>
        /// <param name="procName">存储过程</param>
        /// <param name="dbParameter">参数</param>
        public void ExecuteByProc(string procName, object dbParameter = null)
        {
            try
            {
                using (IDbConnection dbConnection = Connection)
                {
                    dbConnection.Execute(procName, dbParameter, null, null, CommandType.StoredProcedure);
                }

            }
            catch (Exception ex)
            {
                //if (ex is ExceptionEx)
                //{
                throw;
                //}
                //else
                //{
                //    throw ExceptionEx.ThrowBusinessException(ex);
                //}
            }
        }
        /// <summary>
        /// 根据指定数据库执行存储过程
        /// </summary>
        /// <param name="databaseLinkId">数据库主键</param>
        /// <param name="procName">存储过程</param>
        /// <param name="dbParameter">参数</param>
        public void ExecuteByProc(string connString, string procName, object dbParameter = null)
        {
            try
            {
                IDbConnection connection = ConnectionFactory.CreateConnection(connString);
                connection.Open();

                connection.Execute(procName, dbParameter,null, null, CommandType.StoredProcedure);
            }
            catch (Exception ex)
            {
                //if (ex is ExceptionEx)
                //{
                throw;
                //}
                //else
                //{
                //    throw ExceptionEx.ThrowBusinessException(ex);
                //}
            }
        }
        #endregion
    }
}
